package org.jeecg.prod.controller;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.SecurityUtils;
import org.jeecg.client.BizResponse;
import org.jeecg.client.SendUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.CudUtils;
import org.jeecg.prod.dto.MesWoSrcDTO;
import org.jeecg.prod.entity.MesBomHeaderWo;
import org.jeecg.prod.entity.MesWoSrc;
import org.jeecg.prod.service.IMesBomHeaderWoService;
import org.jeecg.prod.service.IMesWoSrcService;
import org.jeecg.trace.service.IMesBomItemWoService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 工单管理
 * @Author: LiCY
 * @Date: 2023-06-16
 * @Version: V1.0
 */
@Api(tags = "工单管理")
@RestController
@RequestMapping("/prod/mesWoSrc")
@Slf4j
public class MesWoSrcController extends JeecgController<MesWoSrc, IMesWoSrcService> {
    @Autowired
    private IMesWoSrcService mesWoSrcService;

    @Autowired
    private IMesBomHeaderWoService mesBomHeaderWoService;
    @Autowired
    private IMesBomItemWoService mesBomItemWoService;
    /**
     * 分页列表查询666
     *
     * @param mesWoSrc
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "工单管理-分页列表查询")
    @ApiOperation(value = "工单管理-分页列表查询", notes = "工单管理-分页列表查询")
    @GetMapping(value = "/list")
    @DS("#header.his")
    public Result<IPage<MesWoSrcDTO>> queryPageList(MesWoSrcDTO mesWoSrc,
                                                 @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                 @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                 HttpServletRequest req) {
        Page<MesWoSrc> page = new Page<MesWoSrc>(pageNo, pageSize);
        IPage<MesWoSrcDTO> pageList = mesWoSrcService.queryPageList(page, mesWoSrc);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param mesWoSrc
     * @return
     */
    @AutoLog(value = "工单管理-添加")
    @ApiOperation(value = "工单管理-添加", notes = "工单管理-添加")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_wo_src:add")
    @PostMapping(value = "/add")
    @DS("#header.his")
    public Result<String> add(@RequestBody MesWoSrc mesWoSrc){
        //mesWoSrcService.save(mesWoSrc);
//        if (StringUtils.isNotBlank(mesWoSrc.getJdeid())) {
//            mesWoSrc.setWoid(mesWoSrc.getJdeid());
//        }
        //if (StringUtils.isBlank(mesWoSrc.getWoid())){
            mesWoSrc.setCtime(new Date());
            Map<String, String> cudMap = CudUtils.getCudMap("create", "mes_wo_src",mesWoSrc.getLine() ,mesWoSrc);
            try {
                BizResponse bizResponse = SendUtils.sendRunCmd(cudMap);
//            if (bizResponse.getData().containsKey("woid")){
//                MesWoSrc mesWoSrc1 = new MesWoSrc();
//                mesWoSrc1.setLine("G02");
//                mesWoSrc1.setPartno(mesWoSrc.getPartno());
//                mesWoSrc1.setWoid(bizResponse.getData().get("woid"));
//                mesWoSrc1.setCtime(new Date());
//                mesWoSrc1.setQty(mesWoSrc.getQty());
//                mesWoSrc1.setJdeid(mesWoSrc.getJdeid());
//                mesWoSrcService.save(mesWoSrc1);
//            }
                System.out.println(bizResponse);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException(e);
            }
//        }else{
//            mesWoSrc.setCtime(new Date());
//            mesWoSrcService.save(mesWoSrc);
//        }

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mesWoSrc
     * @return
     */
    @AutoLog(value = "工单管理-编辑")
    @ApiOperation(value = "工单管理-编辑", notes = "工单管理-编辑")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_wo_src:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    @DS("#header.line")
    public Result<String> edit(@RequestBody MesWoSrc mesWoSrc) {
        mesWoSrc.setCtime(new Date());
        mesWoSrcService.updateByMultiId(mesWoSrc);
        MesBomHeaderWo headerWo = new MesBomHeaderWo();
        headerWo.setWoid(mesWoSrc.getWoid());
        headerWo.setLine(mesWoSrc.getLine());
        headerWo.setQty(mesWoSrc.getQty());
        headerWo.setCtime(mesWoSrc.getCtime());
        headerWo.setPartno(mesWoSrc.getPartno());
        headerWo.setJdeid(mesWoSrc.getJdeid());
        mesBomHeaderWoService.updateByMultiId(headerWo);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过选中对象删除
     *
     * @param mesWoSrc
     * @return
     */
    @AutoLog(value = "工单管理-通过id删除")
    @ApiOperation(value = "工单管理-通过id删除", notes = "工单管理-通过id删除")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_wo_src:delete")
    @RequestMapping(value = "/delete")
    public Result<String> delete(@RequestBody MesWoSrc mesWoSrc) {
        mesWoSrcService.deleteByMultiId(mesWoSrc);
        //删除工单bom
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("WOID", mesWoSrc.getWoid());
        hashMap.put("LINE", mesWoSrc.getLine());
        mesBomHeaderWoService.removeByMap(hashMap);
        mesBomItemWoService.removeByMap(hashMap);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param list
     * @return
     */
    @AutoLog(value = "工单管理-批量删除")
    @ApiOperation(value = "工单管理-批量删除", notes = "工单管理-批量删除")
    //@RequiresPermissions("org.jeecg.modules.demo:mes_wo_src:deleteBatch")
    @RequestMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestBody List<MesWoSrc> list) {
        list.forEach(item -> {
            mesWoSrcService.removeById(item);
        });
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过woid查询
     *
     * @return
     */
    //@AutoLog(value = "工单管理-通过id查询")
    @ApiOperation(value = "工单管理-通过id查询", notes = "工单管理-通过id查询")
    @GetMapping(value = "/queryById")
    @DS("master")
    public Result<MesWoSrc> queryById(@RequestParam(name = "woid", required = true) String woid) {

        String line = mesWoSrcService.getLineByWoId(woid);
        if (StringUtils.isNotBlank(line)){
            DynamicDataSourceContextHolder.clear();
            DynamicDataSourceContextHolder.push("H"+line);
            QueryWrapper<MesWoSrc> queryWrapper = new QueryWrapper<MesWoSrc>().eq("WOID", woid);
            List<MesWoSrc> list = mesWoSrcService.list(queryWrapper);
            if (list.isEmpty()){
                return Result.error("未找到对应数据");
            }
            return Result.OK(list.get(0));
        }else {
            return Result.error("未找到对应数据");
        }

    }

    /**
     * 导出excel
     *
     * @param request
     * @param mesWoSrc
     */
    //@RequiresPermissions("org.jeecg.modules.demo:mes_wo_src:exportXls")
    @RequestMapping(value = "/exportXls")
    @DS("#header.his")
    public ModelAndView exportXls(HttpServletRequest request, MesWoSrc mesWoSrc) {
        return super.exportXls(request, mesWoSrc, MesWoSrc.class, "工单管理");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("mes_wo_src:importExcel")
    @DS("#header.line")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            Workbook workbook = WorkbookFactory.create(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(0);
            Row row = sheet.getRow(0);
            boolean isOrder = false;
            boolean isPartNo = false;
            boolean isQty = false;
            int orderIndex = 0;
            int partNoIndex = 0;
            int qtyIndex = 0;
            for (int i=0;i<=row.getLastCellNum();i++) {
                Cell cell = row.getCell(i);
                if (cell == null) {
                    continue;
                }
                if (cell.getStringCellValue().trim().equalsIgnoreCase("Order")) {
                    isOrder = true;
                    orderIndex = i;
                }
                if (cell.getStringCellValue().trim().equalsIgnoreCase("Material Number")) {
                    isPartNo = true;
                    partNoIndex = i;
                }
                if (cell.getStringCellValue().trim().equalsIgnoreCase("Order quantity (GMEIN)")) {
                    isQty = true;
                    qtyIndex = i;
                }
            }
            DataFormatter formatter = new DataFormatter();
//            Cell cell = row.getCell(1);
            if (isOrder && isPartNo && isQty) {
                List<MesWoSrc> dataList = new ArrayList<>();
                for(int i=1;i<sheet.getLastRowNum()+1;i++) {
                    row = sheet.getRow(i);
                    MesWoSrc woSrc = new MesWoSrc();
                   Cell orderCell = row.getCell(orderIndex);
                    switch (orderCell.getCellType()) {
                        case STRING:
                            String woid = orderCell.getStringCellValue();
                            woSrc.setWoid(woid);
                            woSrc.setJdeid(woid);
                            break;
                        case NUMERIC:
                            // 注意：Excel中的日期也是以NUMERIC类型存储的
                            if (DateUtil.isCellDateFormatted(orderCell)) {
                                System.out.print(orderCell.getDateCellValue() + "\t");
                            } else {
                                System.out.print(orderCell.getNumericCellValue() + "\t");
                                String cellValue = formatter.formatCellValue(orderCell);
                                woSrc.setWoid(cellValue);
                                woSrc.setJdeid(cellValue);
                            }
                            break;
                        case BOOLEAN:
                            System.out.print(orderCell.getBooleanCellValue() + "\t");
                            break;
                        case FORMULA:
                            // 这里可以根据需要处理公式单元格
                            System.out.print(orderCell.getCellFormula() + "\t");
                            break;
                        case BLANK:
                            System.out.print("\t"); // 或者其他方式来处理空白单元格
                            break;
                        // 其他类型可以根据需要添加
                        default:
                            System.out.print("未知类型\t");
                    }

                   Cell partCell = row.getCell(partNoIndex);
                    switch (partCell.getCellType()) {
                        case STRING:
                            String partno = partCell.getStringCellValue();
                            woSrc.setPartno(partno);
                            break;
                        case NUMERIC:
                            // 注意：Excel中的日期也是以NUMERIC类型存储的
                            if (DateUtil.isCellDateFormatted(partCell)) {
                                System.out.print(partCell.getDateCellValue() + "\t");
                            } else {
                                System.out.print(partCell.getNumericCellValue() + "\t");
                                String cellValue = formatter.formatCellValue(partCell);
                                woSrc.setPartno(cellValue);
                            }
                            break;
                        case BOOLEAN:
                            System.out.print(partCell.getBooleanCellValue() + "\t");
                            break;
                        case FORMULA:
                            // 这里可以根据需要处理公式单元格
                            System.out.print(partCell.getCellFormula() + "\t");
                            break;
                        case BLANK:
                            System.out.print("\t"); // 或者其他方式来处理空白单元格
                            break;
                        // 其他类型可以根据需要添加
                        default:
                            System.out.print("未知类型\t");
                    }

                   Cell qtyCell =  row.getCell(qtyIndex);
                   switch (qtyCell.getCellType()) {
                       case STRING:
                           String qty = qtyCell.getStringCellValue();
                           woSrc.setQty(new BigDecimal(qty));
                           break;
                       case NUMERIC:
                           // 注意：Excel中的日期也是以NUMERIC类型存储的
                           if (DateUtil.isCellDateFormatted(qtyCell)) {
                               System.out.print(qtyCell.getDateCellValue() + "\t");
                           } else {
                               System.out.print(qtyCell.getNumericCellValue() + "\t");
                               woSrc.setQty(BigDecimal.valueOf(qtyCell.getNumericCellValue()));
                           }
                           break;
                       case BOOLEAN:
                           System.out.print(qtyCell.getBooleanCellValue() + "\t");
                           break;
                       case FORMULA:
                           // 这里可以根据需要处理公式单元格
                           System.out.print(qtyCell.getCellFormula() + "\t");
                           break;
                       case BLANK:
                           System.out.print("\t"); // 或者其他方式来处理空白单元格
                           break;
                       // 其他类型可以根据需要添加
                       default:
                           System.out.print("未知类型\t");
                   }
                    woSrc.setCtime(new Date());
                    woSrc.setLine("BG150");
                    dataList.add(woSrc);
                }
                dataList.forEach(item -> {
                    service.save(item);
                });
                return Result.ok("文件导入成功！数据行数：" + dataList.size());
            } else {
                return super.importExcel(request, response, MesWoSrc.class);
            }
        }


//        return super.importExcel(request, response, MesWoSrc.class);
        return null;
    }

}
